const OSS = require("ali-oss");
const moment = require("moment");
const fs = require("fs");
const client = new OSS({
  region: "oss-cn-hangzhou",
  accessKeyId: "LTAI5tCr3iK3XLHYMygN1AV3",
  accessKeySecret: "kh4fBAI8LWOoDjtLkhZmFoAj0b4gJw",
  bucket: "blog-wzy",
});
const uploadOss = async (ctx, next) => {
  const time = moment().valueOf();
  const { titleImg } = ctx.request.body;

  if (titleImg) {
    const imgData = titleImg.replace(/^data:image\/\w+;base64,/, "");
    const imgBuffer = Buffer.from(imgData, "base64");
    const result = await client.put(`/image/img${time}.png`, imgBuffer);
    console.log(result, "oss");
    ctx.request.body.titleImg = result.url;
  } else {
    ctx.request.body.titleImg = "";
  }
  await next();
};

const uploadImg = async (ctx, next) => {
  console.log(
    ctx.request.body,
    "body",
    ctx.request.files["imgUrl[]"],
    ctx.request.files.imgUrl
  );
  const time = moment().valueOf();
  const { imgUrl } = ctx.request.files;
  let arr = ctx.request.files["imgUrl[]"];
  if (arr&&arr.length > 1) {
    console.log(arr,"arrImg")
    const strArr = [];
    for (let item of arr) {
      let readStream = fs.createReadStream(item.filepath);
      const result = await client.put(`/image/talk${item.newFilename}.png`, readStream);
      console.log(result.url, "oss");
      strArr.push(result.url);
      console.log(strArr, "加入");
      fs.unlink(item.filepath, (err) => {
        if (err) {
          console.error("删除文件时发生错误：", err);
        } else {
          console.log("暂时图片删除成功");
        }
      });
    }
    console.log("tmpstr", strArr.join(","));
    ctx.request.body.imgUrl = strArr.join(",");``
  } else if (imgUrl) {
    const readStream = fs.createReadStream(imgUrl.filepath);
    const result = await client.put(`/image/talk${time}.png`, readStream);
    fs.unlink(imgUrl.filepath, (err) => {
      if (err) {
        console.error("删除文件时发生错误：", err);
      } else {
        console.log("暂时图片删除成功");
      }
    });
    console.log(result, "oss");
    ctx.request.body.imgUrl = result.url;
  } else {
    ctx.request.body.imgUrl = "";
  }
  await next();
};

module.exports = { uploadOss, uploadImg };
